import {createRouter, createWebHistory, type RouteRecordRaw} from 'vue-router'
import {useUserStore} from "@/stores/user";
import pinia from "@/stores";
import {useRouterStore} from "@/stores/router";
import {loadRouter} from "@/router/backEnd";

const views = import.meta.glob("@/views/**/*.vue")
const routeStore = useRouterStore(pinia)

const loadComponent = (routerList: RouteRecordRaw[]) => {
  routerList.forEach((router:RouteRecordRaw) => {
    if (router.meta){
      const component = router.meta.component as string
      if (component) {
        router.component = views[component]
      }
    }
    if (router.children && router.children.length > 0) {
      loadComponent(router.children)
    }
  })
}
/**
 * 公共静态路由
 */
export const staticRouter:RouteRecordRaw[] = [{
  name: 'login',
  path: '/login',
  component: () => import('@/views/login/index.vue')
}]
/**
 * 所有页面的父级页面
 */
export const layoutRouter : RouteRecordRaw = {
  name: 'layout',
  path: '',
  redirect: '/dashboard',
  component: () => import('@/layout/index.vue'),
  children:[],
  meta: {
    title: '首页'
  }
}

/**
 * 创建路由实例
 */
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...staticRouter]
})

router.beforeEach( (to, from, next) => {
  const userStore = useUserStore(pinia)
  if (!userStore.loginState && to.path !== '/login') {
    next({path: '/login'})
  } else {
    const routerList = routeStore.getRouterList();
    if (routerList.length > 0) {
      next()
    }else {
      loadRouter().then(() => {
        router.replace({path: to.path, query: to.query})
      })
    }
  }
})

export default router
